package com.example.munidingwei

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class LocationViewModel(application: Application) : AndroidViewModel(application) {
    // 使用全局单例LocationService，确保后台持续运行
    private val locationService = MainApplication.getLocationService(application)
    private val backendClient = MainApplication.getBackendClient(application)
    
    private val _uiState = MutableStateFlow(LocationUiState())
    val uiState: StateFlow<LocationUiState> = _uiState.asStateFlow()
    
    init {
        viewModelScope.launch {
            locationService.currentLocation.collect { location ->
                _uiState.value = _uiState.value.copy(
                    currentLocation = location,
                    isSimulating = locationService.isLocationSimulated()
                )
            }
        }
        
        viewModelScope.launch {
            locationService.locationHistory.collect { history ->
                _uiState.value = _uiState.value.copy(
                    locationHistory = history
                )
            }
        }
        
        // 监听后台连接状态
        viewModelScope.launch {
            backendClient.isConnected.collect { connected ->
                _uiState.value = _uiState.value.copy(
                    isConnectedToBackend = connected
                )
            }
        }
        
        // 加载保存的服务器地址
        loadSavedServerUrl()
        
        // 自动连接到默认服务器
        autoConnectToDefaultServer()
    }
    
    /**
     * 加载保存的服务器地址
     */
    private fun loadSavedServerUrl() {
        try {
            val prefs = getApplication<Application>().getSharedPreferences("app_prefs", android.content.Context.MODE_PRIVATE)
            val savedUrl = prefs.getString("server_url", _uiState.value.currentServerUrl) ?: _uiState.value.currentServerUrl
            
            // 更新状态
            _uiState.value = _uiState.value.copy(
                currentServerUrl = savedUrl
            )
            
            android.util.Log.d("LocationViewModel", "📥 已加载保存的服务器地址: $savedUrl")
        } catch (e: Exception) {
            android.util.Log.e("LocationViewModel", "❌ 加载服务器地址失败: ${e.message}", e)
        }
    }
    
    /**
     * 自动连接到默认服务器
     */
    private fun autoConnectToDefaultServer() {
        viewModelScope.launch {
            try {
                android.util.Log.d("LocationViewModel", "========================================")
                android.util.Log.d("LocationViewModel", "🚀 App启动，自动连接到默认服务器")
                android.util.Log.d("LocationViewModel", "========================================")
                
                // 获取当前的服务器地址（已经从SharedPreferences加载）
                val serverUrl = _uiState.value.currentServerUrl
                
                android.util.Log.d("LocationViewModel", "服务器地址: $serverUrl")
                
                // 延迟1秒后连接，等待UI初始化完成
                kotlinx.coroutines.delay(1000)
                
                // 自动连接
                connectToBackend(serverUrl)
                
                android.util.Log.d("LocationViewModel", "✅ 已发起自动连接请求")
                
            } catch (e: Exception) {
                android.util.Log.e("LocationViewModel", "❌ 自动连接失败: ${e.message}", e)
            }
        }
    }
    
    fun requestLocationPermission() {
        _uiState.value = _uiState.value.copy(
            showPermissionDialog = true
        )
    }
    
    fun onPermissionResult(granted: Boolean) {
        _uiState.value = _uiState.value.copy(
            showPermissionDialog = false,
            hasLocationPermission = granted
        )
        
        if (granted) {
            getCurrentLocation()
        }
    }
    
    fun getCurrentLocation() {
        locationService.getCurrentLocation()
    }
    
    fun startLocationUpdates() {
        locationService.startLocationUpdates()
    }
    
    fun simulateLocation(latitude: Double, longitude: Double) {
        locationService.simulateLocation(latitude, longitude)
    }
    
    fun enableSystemMockLocation(): Boolean {
        return locationService.enableSystemMockLocation()
    }
    
    fun setSystemMockLocation(latitude: Double, longitude: Double, accuracy: Float = 5.0f) {
        locationService.setSystemMockLocation(latitude, longitude, accuracy)
    }
    
    fun disableSystemMockLocation() {
        locationService.disableSystemMockLocation()
    }
    
    fun getSystemMockStatus(): String {
        return locationService.getSystemMockStatus()
    }
    
    fun hasMockLocationPermission(): Boolean {
        return locationService.hasMockLocationPermission()
    }
    
    fun isSystemMockEnabled(): Boolean {
        return locationService.isSystemMockEnabled()
    }
    
    fun stopSimulation() {
        locationService.stopSimulation()
        // 立即更新UI状态
        _uiState.value = _uiState.value.copy(
            isSimulating = false
        )
    }
    
    fun clearHistory() {
        locationService.clearHistory()
    }
    
    fun showSimulationDialog() {
        _uiState.value = _uiState.value.copy(
            showSimulationDialog = true
        )
    }
    
    fun hideSimulationDialog() {
        _uiState.value = _uiState.value.copy(
            showSimulationDialog = false
        )
    }
    
    fun showHistoryDialog() {
        _uiState.value = _uiState.value.copy(
            showHistoryDialog = true
        )
    }
    
    fun hideHistoryDialog() {
        _uiState.value = _uiState.value.copy(
            showHistoryDialog = false
        )
    }
    
    fun showSystemMockDialog() {
        _uiState.value = _uiState.value.copy(
            showSystemMockDialog = true
        )
    }
    
    fun hideSystemMockDialog() {
        _uiState.value = _uiState.value.copy(
            showSystemMockDialog = false
        )
    }
    
    /**
     * 搜索地址
     */
    fun searchAddress(address: String) {
        _uiState.value = _uiState.value.copy(isSearching = true)
        
        locationService.searchAddress(address) { results ->
            _uiState.value = _uiState.value.copy(
                searchResults = results,
                isSearching = false
            )
        }
    }
    
    /**
     * 清除搜索结果
     */
    fun clearSearchResults() {
        _uiState.value = _uiState.value.copy(
            searchResults = emptyList()
        )
    }
    
    /**
     * 选择搜索结果并设置为模拟位置
     */
    fun selectSearchResult(result: com.example.munidingwei.ui.components.SearchResult) {
        // 设置模拟位置（内部会自动启用Mock Provider）
        setSystemMockLocation(result.latitude, result.longitude, 5.0f)
        // 清除搜索结果
        clearSearchResults()
    }
    
    /**
     * 连接到后台服务器
     */
    fun connectToBackend(serverUrl: String? = null) {
        locationService.connectToBackend(serverUrl)
    }
    
    /**
     * 断开后台连接
     */
    fun disconnectFromBackend() {
        locationService.disconnectFromBackend()
    }
    
    /**
     * 切换后台连接状态
     */
    fun toggleBackendConnection(serverUrl: String? = null) {
        if (_uiState.value.isConnectedToBackend) {
            disconnectFromBackend()
        } else {
            connectToBackend(serverUrl)
        }
    }
    
    /**
     * 显示后台连接对话框
     */
    fun showBackendDialog() {
        _uiState.value = _uiState.value.copy(
            showBackendDialog = true
        )
    }
    
    /**
     * 隐藏后台连接对话框
     */
    fun hideBackendDialog() {
        _uiState.value = _uiState.value.copy(
            showBackendDialog = false
        )
    }
    
    /**
     * 显示服务器配置对话框
     */
    fun showServerConfigDialog() {
        _uiState.value = _uiState.value.copy(
            showServerConfigDialog = true
        )
    }
    
    /**
     * 隐藏服务器配置对话框
     */
    fun hideServerConfigDialog() {
        _uiState.value = _uiState.value.copy(
            showServerConfigDialog = false
        )
    }
    
    /**
     * 保存服务器地址
     */
    fun saveServerUrl(url: String) {
        try {
            // 保存到SharedPreferences
            val prefs = getApplication<Application>().getSharedPreferences("app_prefs", android.content.Context.MODE_PRIVATE)
            prefs.edit().putString("server_url", url).apply()
            
            // 更新状态
            _uiState.value = _uiState.value.copy(
                currentServerUrl = url
            )
            
            android.util.Log.d("LocationViewModel", "✅ 服务器地址已保存: $url")
        } catch (e: Exception) {
            android.util.Log.e("LocationViewModel", "❌ 保存服务器地址失败: ${e.message}", e)
        }
    }
}

data class LocationUiState(
    val currentLocation: LocationData? = null,
    val locationHistory: List<LocationData> = emptyList(),
    val hasLocationPermission: Boolean = false,
    val isSimulating: Boolean = false,
    val showPermissionDialog: Boolean = false,
    val showSimulationDialog: Boolean = false,
    val showSystemMockDialog: Boolean = false,
    val showHistoryDialog: Boolean = false,
    val showBackendDialog: Boolean = false,
    val showServerConfigDialog: Boolean = false,
    val searchResults: List<com.example.munidingwei.ui.components.SearchResult> = emptyList(),
    val isSearching: Boolean = false,
    val isConnectedToBackend: Boolean = false,
    val currentServerUrl: String = "https://myedu.webn.cc/backend-php/api.php"
)
